<template>
  <view class="todo-container">
    <!-- 顶部标题栏 -->
    <view class="header">
      <view class="header-left">
        <text class="title">待办事项</text>
        <text class="subtitle">Today's Tasks</text>
      </view>
      <button class="add-btn" @click="showAddModal">
        <text class="add-icon">+</text>
        <text>新建</text>
      </button>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-card">
      <view class="stats-item">
        <text class="stats-number">{{ totalCount }}</text>
        <text class="stats-label">总计</text>
      </view>
      <view class="stats-divider"></view>
      <view class="stats-item">
        <text class="stats-number">{{ completedCount }}</text>
        <text class="stats-label">已完成</text>
      </view>
      <view class="stats-divider"></view>
      <view class="stats-item">
        <text class="stats-number">{{ completionPercentage }}%</text>
        <text class="stats-label">完成率</text>
      </view>
    </view>

    <!-- 日期筛选 -->
    <view class="date-filter">
      <scroll-view class="date-scroll" scroll-x>
        <view
            v-for="date in dateFilters"
            :key="date.value"
            class="date-tab"
            :class="{ active: currentFilter === date.value }"
            @click="changeFilter(date.value)"
        >
          <text class="date-label">{{ date.label }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 待办列表 -->
    <view class="todo-list">
      <view
          v-for="todo in filteredTodos"
          :key="todo.id"
          class="todo-card"
          :class="{
          'completed': todo.completed,
          'priority-high': todo.priority === 'high',
          'priority-medium': todo.priority === 'medium'
        }"
      >
        <view class="todo-checkbox" @click="toggleComplete(todo)">
          <view class="checkbox" :class="{ checked: todo.completed }">
            <text v-if="todo.completed" class="checkmark">✓</text>
          </view>
        </view>

        <view class="todo-content" @click="editTodo(todo)">
          <view class="todo-header">
            <text class="todo-title">{{ todo.title }}</text>
            <view class="todo-badges">
              <text v-if="todo.priority === 'high'" class="priority-badge high">紧急</text>
              <text v-if="todo.priority === 'medium'" class="priority-badge medium">重要</text>
              <text v-if="isToday(todo.dueDate)" class="date-badge today">今天</text>
              <text v-else-if="isOverdue(todo.dueDate)" class="date-badge overdue">逾期</text>
            </view>
          </view>

          <text v-if="todo.description" class="todo-desc">{{ todo.description }}</text>

          <view class="todo-meta">
            <text class="todo-date">
              <text class="date-icon">📅</text>
              {{ formatDate(todo.dueDate) }}
            </text>
            <text v-if="todo.completed" class="completed-time">
              完成于 {{ formatTime(todo.completedAt) }}
            </text>
          </view>
        </view>

        <view class="todo-actions">
          <button class="action-btn edit" @click.stop="editTodo(todo)">
            <text class="action-icon">✏️</text>
          </button>
          <button class="action-btn copy" @click.stop="copyTodo(todo)">
            <text class="action-icon">📋</text>
          </button>
          <button class="action-btn delete" @click.stop="deleteTodo(todo)">
            <text class="action-icon">🗑️</text>
          </button>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="filteredTodos.length === 0" class="empty-state">
        <image class="empty-image" src="/static/empty-todo.png" mode="aspectFit"></image>
        <text class="empty-text">暂无待办事项</text>
        <text class="empty-subtext">点击下方按钮创建第一个待办事项</text>
      </view>
    </view>

    <!-- 添加/编辑弹窗 -->
    <uni-popup ref="popup" type="center" :mask-click="false">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">{{ editingTodo ? '编辑待办事项' : '新建待办事项' }}</text>
        </view>

        <view class="popup-body">
          <text class="form-label">任务标题</text>
          <input
              class="uni-input"
              focus
              placeholder="请输入任务标题"
              v-model="currentTodo.title"
              maxlength="50"
          />
          <text class="char-count">{{ currentTodo.title.length }}/50</text>

          <text class="form-label">任务描述</text>
          <textarea
              class="form-textarea"
              placeholder="请输入任务描述（可选）"
              v-model="currentTodo.description"
              maxlength="200"
          />
          <text class="char-count">{{ currentTodo.description.length }}/200</text>

          <!-- 日期和优先级 -->
          <view>
            <view class="form-group">
              <text class="form-label">截止日期</text>
              <picker
                  mode="date"
                  :value="currentTodo.dueDate"
                  @change="onDateChange"
                  class="date-picker"
              >
                <view class="picker-display">
                  <text class="picker-text">{{ currentTodo.dueDate || '选择日期' }}</text>
                  <text class="picker-icon">📅</text>
                </view>
              </picker>
            </view>

            <view class="form-group">
              <text class="form-label">优先级</text>
              <picker
                  mode="selector"
                  :range="priorityOptions"
                  :value="currentPriorityIndex"
                  @change="onPriorityChange"
                  class="priority-picker"
              >
                <view class="picker-display">
                  <text class="picker-text">{{ priorityOptions[currentPriorityIndex] }}</text>
                  <text class="picker-icon">⬇️</text>
                </view>
              </picker>
            </view>
          </view>
        </view>

        <view class="popup-footer">
          <button class="btn btn-cancel" @click="closeModal">取消</button>
          <button class="btn btn-confirm" @click="saveTodo">保存</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { listTodos, createTodo, updateTodo, deleteTodo, completeTodo } from '@/api/todo/index.js'

// 定义 Todo 类型
interface Todo {
  id: string;
  title: string;
  description: string;
  dueDate: string;
  priority: 'low' | 'medium' | 'high';
  completed: boolean;
  completedAt?: string;
  createdAt?: string;
  userId?: string;
}

// 定义 Popup 引用类型
interface PopupRef {
  open: (type: string) => void;
  close: () => void;
}

export default {
  data() {
    return {
      todoList: [] as Todo[], // 添加类型断言
      editingTodo: null as Todo | null,
      currentFilter: 'all',
      currentPriorityIndex: 0,
      priorityOptions: ['普通', '重要', '紧急'],
      priorityValues: ['low', 'medium', 'high'],
      currentTodo: this.getDefaultTodo(),
      dateFilters: [
        { label: '全部', value: 'all' },
        { label: '今天', value: 'today' },
        { label: '未来', value: 'future' },
        { label: '逾期', value: 'overdue' },
        { label: '已完成', value: 'completed' }
      ]
    }
  },

  computed: {
    totalCount(): number {
      return this.todoList.length
    },

    completedCount(): number {
      return this.todoList.filter((todo: Todo) => todo.completed).length
    },

    completionPercentage(): number {
      if (this.totalCount === 0) return 0
      return Math.round((this.completedCount / this.totalCount) * 100)
    },

    filteredTodos(): Todo[] {
      const today = new Date().toDateString()
      const now = new Date()

      switch (this.currentFilter) {
        case 'today':
          return this.todoList.filter((todo: Todo) =>
              !todo.completed && new Date(todo.dueDate).toDateString() === today
          )
        case 'future':
          return this.todoList.filter((todo: Todo) =>
              !todo.completed && new Date(todo.dueDate) > now
          )
        case 'overdue':
          return this.todoList.filter((todo: Todo) =>
              !todo.completed && new Date(todo.dueDate) < now &&
              new Date(todo.dueDate).toDateString() !== today
          )
        case 'completed':
          return this.todoList.filter((todo: Todo) => todo.completed)
        default:
          return this.todoList.filter((todo: Todo) => !todo.completed)
      }
    }
  },

  onLoad() {
    this.loadTodos()
  },

  methods: {
    getDefaultTodo(): Partial<Todo> {
      return {
        title: '',
        description: '',
        dueDate: this.getTodayDate(),
        priority: 'low'
      }
    },

    getTodayDate(): string {
      const date = new Date()
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    formatDate(dateString: string): string {
      if (!dateString) return ''
      const date = new Date(dateString)
      const today = new Date()
      const tomorrow = new Date(today)
      tomorrow.setDate(tomorrow.getDate() + 1)

      if (date.toDateString() === today.toDateString()) {
        return '今天'
      } else if (date.toDateString() === tomorrow.toDateString()) {
        return '明天'
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`
      }
    },

    formatTime(timestamp: string): string {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },

    isToday(dateString: string): boolean {
      if (!dateString) return false
      return new Date(dateString).toDateString() === new Date().toDateString()
    },

    isOverdue(dateString: string): boolean {
      if (!dateString) return false
      const date = new Date(dateString)
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      return date < today
    },

    async loadTodos() {
      try {
        const userId = 'current_user_id'
        const response = await listTodos({ userId })
        this.todoList = response.data || []
      } catch (error) {
        console.error('加载待办事项失败:', error)
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },

    showAddModal() {
      this.editingTodo = null
      this.currentTodo = this.getDefaultTodo()
      this.currentPriorityIndex = 0
      const popup = this.$refs.popup as PopupRef
      popup.open('center')
    },

    editTodo(todo: Todo) {
      this.editingTodo = todo
      this.currentTodo = { ...todo }
      this.currentPriorityIndex = this.priorityValues.indexOf(todo.priority)
      if (this.currentPriorityIndex === -1) {
        this.currentPriorityIndex = 0
      }
      const popup = this.$refs.popup as PopupRef
      popup.open('center')
    },

    closeModal() {
      const popup = this.$refs.popup as PopupRef
      popup.close()
    },

    onDateChange(e: any) {
      this.currentTodo.dueDate = e.detail.value
    },

    onPriorityChange(e: any) {
      const index = Number(e.detail.value)
      this.currentPriorityIndex = index
      this.currentTodo.priority = this.priorityValues[index]
    },

    async saveTodo() {
      if (!this.currentTodo.title?.trim()) {
        uni.showToast({ title: '请填写任务标题', icon: 'none' })
        return
      }

      try {
        if (this.editingTodo && this.editingTodo.id) {
          const response = await updateTodo(this.editingTodo.id, this.currentTodo)
          const index = this.todoList.findIndex((todo: Todo) => todo.id === this.editingTodo!.id)
          if (index !== -1) {
            this.todoList.splice(index, 1, response.data || this.currentTodo)
          }
          uni.showToast({ title: '更新成功' })
        } else {
          const todoData = {
            ...this.currentTodo,
            userId: 'current_user_id',
            createdAt: new Date().toISOString()
          }
          const response = await createTodo(todoData)
          this.todoList.unshift(response.data || todoData)
          uni.showToast({ title: '添加成功' })
        }
        this.closeModal()
        await this.loadTodos()
      } catch (error) {
        console.error('保存待办事项失败:', error)
        uni.showToast({ title: '保存失败', icon: 'none' })
      }
    },

    async toggleComplete(todo: Todo) {
      try {
        const updatedTodo = {
          ...todo,
          completed: !todo.completed,
          completedAt: !todo.completed ? new Date().toISOString() : null
        }

        const response = await completeTodo(updatedTodo)
        const index = this.todoList.findIndex((item: Todo) => item.id === todo.id)
        if (index !== -1) {
          this.todoList.splice(index, 1, response.data || updatedTodo)
        }

        const message = updatedTodo.completed ? '任务已完成' : '已重新打开任务'
        uni.showToast({ title: message })
        await this.loadTodos()
      } catch (error) {
        console.error('更新状态失败:', error)
        uni.showToast({ title: '更新失败', icon: 'none' })
      }
    },

    async deleteTodo(todo: Todo) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除"${todo.title}"吗？`,
        confirmColor: '#FF4757',
        success: async (res) => {
          if (res.confirm) {
            try {
              await deleteTodo(todo.id!)
              this.todoList = this.todoList.filter((item: Todo) => item.id !== todo.id)
              uni.showToast({ title: '删除成功' })
              await this.loadTodos()
            } catch (error) {
              console.error('删除失败:', error)
              uni.showToast({ title: '删除失败', icon: 'none' })
            }
          }
        },
        fail: (error) => {
          console.error('弹窗显示失败:', error)
          uni.showToast({ title: '操作失败', icon: 'none' })
        }
      })
    },

    copyTodo(todo: Todo) {
      const newTodo = {
        title: `${todo.title}`,
        description: todo.description,
        dueDate: todo.dueDate,
        priority: todo.priority
      }
    
      this.currentTodo = { ...newTodo }
      
      // 修复类型问题 - 确保 priority 是有效的字符串
      const priority = newTodo.priority || 'low'
      this.currentPriorityIndex = this.priorityValues.indexOf(priority)
      
      if (this.currentPriorityIndex === -1) {
        this.currentPriorityIndex = 0
      }
    
      this.editingTodo = null
      const popup = this.$refs.popup as PopupRef
      popup.open('center')
    },

    changeFilter(filter: string) {
      this.currentFilter = filter
    }
  }
}
</script>

<style src="./index.css" scoped></style>